package org.p2psimulator.entity.protocol.hibrid;

import org.p2psimulator.entity.Peer;
import org.p2psimulator.entity.protocol.Protocol;
import org.p2psimulator.entity.protocol.structured.ChordProtocol;
import org.p2psimulator.entity.protocol.unstructured.FloodProtocol;
import org.p2psimulator.exceptions.OverlayNetworkException;
import org.p2psimulator.engine.Environment;
import org.p2psimulator.entity.overlaynetwork.GnutellaOverlay;
import org.p2psimulator.entity.protocol.unstructured.p2prep.P2PRepProtocol;

public abstract class HibridProtocol extends Protocol {

    protected FloodProtocol gnutella;
    protected ChordProtocol chord;

    public HibridProtocol(Environment enviroment) {
        super(enviroment);
        gnutella = new FloodProtocol(enviroment);
        chord = new ChordProtocol(enviroment);
    }

    @Override
    public String joinNetworkRequestCycle(Peer p) {

        String ret = "[ HIBRID JOIN CYCLE - REQUEST - ";
        try {
            //SystemLogger.transactionLogger.info(gnutella.joinNetworkRequestCycle(p));
            //SystemLogger.transactionLogger.info(chord.joinNetworkRequestCycle(p));
            env.getChordOverlayNetwork().joinNetwork(p.getId());

            ret += "CHORD OVERLAY: DONE - ";
            env.getFloodOverlayNetwork().joinNetwork(p.getId());

            ret += "GNUTELLA OVERLAY: DONE - ";

            p.setOnline(true);
        } catch (OverlayNetworkException ex) {
            ex.printStackTrace();
            return "";
        }
        ret += " ]";
        return ret;
    }

    @Override
    public String joinNetworkResponseCycle(Peer p) {
        //SystemLogger.transactionLogger.info(gnutella.joinNetworkResponseCycle(p));
        //SystemLogger.transactionLogger.info(chord.joinNetworkResponseCycle(p));
        String ret = "[ HIBRID JOIN CYCLE - RESPONSE - OK ]";
        return ret;
    }

    @Override
    public String leaveNetworkCycle(Peer p) {
        String ret = "[ HIBRID LEAVE CYCLE - ";
        try {
            GnutellaOverlay overlay = (GnutellaOverlay) env.getFloodOverlayNetwork();
            overlay.leaveNetwork(p.getId());

            ret += " GNUTELLA LEAVE CYCLE: DONE - ";

            if (p.isOnline()) 
            env.getChordOverlayNetwork().leaveNetwork(p.getId());

            ret += " CHORD LEAVE CYCLE: DONE ";
            p.setOnline(false);

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        ret += " ]";
        return ret;
    }
}
